package com.example.carrierapp.ui.main.goodssource.details

import android.annotation.SuppressLint
import android.content.Intent
import android.databinding.DataBindingUtil
import android.databinding.ViewDataBinding
import android.os.Handler
import android.os.Message
import android.support.design.widget.TabLayout
import android.support.v4.view.PagerAdapter
import android.view.View
import android.view.ViewGroup
import com.example.carrierapp.base.DataBindingActivity
import com.example.carrierapp.config.gone
import com.example.carrierapp.config.show
import com.example.carrierapp.config.toast
import com.example.carrierapp.util.AppUtil
import com.example.carrierapp.viewmodel.viewmodel.GoodsSourceDetailsModel
import com.example.lb.fingerdemo.BR
import com.example.lb.fingerdemo.R
import kotlinx.android.synthetic.main.activity_goods_source_details.*
import java.util.*

class GoodsSourceDetailsActivity : DataBindingActivity<GoodsSourceDetailsModel, GoodsSourceDetailsContract.View, GoodsSourceDetailsPresenter>()
        , GoodsSourceDetailsContract.View {

    private val lineId by lazy {
        intent.getIntExtra("lineId", 0)
    }

    private lateinit var handler: Handler

    override fun createPresenter() = GoodsSourceDetailsPresenter(this)

    override fun getTitleString() = ""

    override fun getContentView() = R.layout.activity_goods_source_details

    override fun initData() {
        model.isCombination = intent.getBooleanExtra("isCombination", false)
        model.details = intent.getBooleanExtra("isDetails", false)
        model.robbingPattern = intent.getIntExtra("robbingPattern", 1)
        model.biddingId = intent.getIntExtra("biddingId", 0)
        fetchData()
        handler = @SuppressLint("HandlerLeak")
        object : Handler() {
            override fun handleMessage(msg: Message?) {
                when (msg?.what) {
                    0x01 -> {
                        if (model.countDownSeconds > 0) {
                            model.countDownSeconds -= 1
                            model.notifyTime()
                            sendEmptyMessageDelayed(0x01, 1000)
                        }
                    }
                }
            }
        }
    }

    override fun initView() {
        if (model.isCombination)
            line_menu.show()
    }

    private fun fetchData() {
        val lineId = if (model.isCombination) 0 else this.lineId
        if (model.details)
            mPresenter.fetchGoodsRecordDetails(model.biddingId, lineId)
        else
            mPresenter.fetchGoodsSourceDetails(model.biddingId, lineId)
    }

    fun doBid(view: View) {
        if (model.countDownSeconds <= 0) {
            toast("竞抢已结束")
            finish()
            return
        }
        model.biddingLineList?.forEachIndexed { index, item ->
            if (item.offer == 0f) {
                if (model.biddingLineList?.size ?: 0 > 1)
                    toast("线路${index + 1}未报价，请输入价格")
                else
                    toast("请输入价格")
                return
            }
        }
        mPresenter.doBid(model.biddingLineList)
    }

    fun callPhone(view: View) {
        AppUtil.callNumber(view.context, model.adminPhone)
    }

    override fun onFetchSuccess(rows: GoodsSourceDetailsModel) {
        if (model.onDeal) {
            model.onDeal = false
            model.bidMark = rows.bidMark
            return
        }
        rows.details = model.details
        rows.robbingPattern = model.robbingPattern
        rows.isCombination = model.isCombination
        notifyModel(rows)
        model.biddingLineList?.forEach {
            it.robbingPattern = rows.robbingPattern
            it.isDetails = rows.details
            it.adminName = rows.adminName
            if (rows.robbingPattern == 3) {
                it.offer = it.maxPrice
                it.price = it.maxPrice.toString()
            } else {
                if (model.details) {
                    if (it.offer == 0f)
                        it.price = ""
                    else
                        it.price = it.offer.toString()
                }
            }
        }
        if (model.details.not())
            handler.sendEmptyMessage(0x01)
        pager.offscreenPageLimit = model.biddingLineList?.size ?: 0
        pager.adapter = object : PagerAdapter() {
            override fun isViewFromObject(p0: View, p1: Any) = p0 == p1

            override fun getCount() = rows.biddingLineList?.size ?: 0

            override fun getPageTitle(position: Int) = "线路${position + 1}"

            override fun instantiateItem(container: ViewGroup, position: Int): Any {
                val binding = DataBindingUtil.inflate<ViewDataBinding>(layoutInflater, R.layout.layout_goods_details, container, false)
                binding.setVariable(BR.model, rows.biddingLineList?.get(position))
                binding.executePendingBindings()
                container.addView(binding.root)
                return binding.root
            }

            override fun destroyItem(container: ViewGroup, position: Int, `object`: Any) {
                container.removeView(`object` as View?)
            }
        }
        line_menu.setupWithViewPager(pager)
    }

    override fun onFetchError() {

    }

    override fun onBidSuccess() {
        toast(if (model.robbingPattern == 3) {
            model.onDeal = true
            model.details = true
            handler.removeMessages(0x01)
            Timer().schedule(object : TimerTask() {
                override fun run() {
                    fetchData()
                }
            }, 8000)
            "抢单成功"
        } else {
            confirm_view.gone()
            model.biddingLineList?.forEach {
                it.isDetails = true
            }
            "报价成功"
        })
        if (model.robbingPattern != 3) {
            sendBroadcast(Intent("goods_source").putExtra("biddingId", model.biddingId))
        }
    }

    override fun onBidError() {

    }

}
